// Content script
// Author: Chaitanya Gharpure (chaitanyag@google.com)
// Quick Links

var powerkey;
var linklist;

function init() {
  powerkey = new PowerKey('main');
  linklist = powerkey.createCompletionList('a',
      function(node) {
        return PowerKey.leftTrim(
            PowerKey.rightTrim(node.textContent)) != '';
      },
      function(node) {
        return node.textContent;
      }, true);
  powerkey.createCompletionField(document.body, 50, onSelection, null,
      linklist, false);
  powerkey.attachHandlerAndListen(document, 'keyup', null, action_map);
  powerkey.setAutoHideCompletionField(true);
}

function onSelection(text, index, elem, args) {
  clickElem(elem);
}

function onShowPowerKey(evt) {
  if (!(evt.target instanceof HTMLInputElement)) {
    powerkey.updateCompletionField('visible');
  }
}

var action_map = {
  '190' : {'main' : ['main', onShowPowerKey]}
}

/**
 * Dispatches a left click event on the element that is the targetNode.
 * Clicks go in the sequence of mousedown, mouseup, and click.
 * @param {Node} targetNode The target node of this operation.
 * @param {boolean} shiftKey Specifies if shift is held down.
 */
function clickElem(targetNode){
  var activeDoc = document;
  //Send a mousedown
  var evt = activeDoc.createEvent('MouseEvents');
  evt.initMouseEvent('mousedown', true, true, activeDoc.defaultView,
                     1, 0, 0, 0, 0, false, false, false, false, 0, null);
  //Use a try block here so that if the AJAX fails and it is a link,
  //it can still fall through and retry by setting the document.location.
  try{
    targetNode.dispatchEvent(evt);
  } catch (e){}
  //Send a mouse up
  evt = activeDoc.createEvent('MouseEvents');
  evt.initMouseEvent('mouseup', true, true, activeDoc.defaultView,
                     1, 0, 0, 0, 0, false, false, false, false, 0, null);
  //Use a try block here so that if the AJAX fails and it is a link,
  //it can still fall through and retry by setting the document.location.
  try{
    targetNode.dispatchEvent(evt);
  } catch (e){}
  //Send a click
  evt = activeDoc.createEvent('MouseEvents');
  evt.initMouseEvent('click', true, true, activeDoc.defaultView,
                     1, 0, 0, 0, 0, false, false, false, false, 0, null);
  //Use a try block here so that if the AJAX fails and it is a link,
  //it can still fall through and retry by setting the document.location.
  try{
    targetNode.dispatchEvent(evt);
  } catch (e){}
  //Clicking on a link does not cause traversal because of script
  //privilege limitations. The traversal has to be done by setting
  //document.location.
  var href = targetNode.getAttribute('href');
  if ((targetNode.tagName == 'A') &&
      (href != '#')){
    document.location = targetNode.href;
  }
};

init();
